package com.by.toolkit.model;

import com.by.toolkit.consts.GlobalConst;
import com.by.toolkit.utils.ByIfNotEmptyUtil;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;

/**
 * 分页统一响应参数
 *
 * @author YanBingHao
 * @since 2023/12/27
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ESPageResp<T> implements Serializable {

    private Long totalSize;

    private List<Object> preSearchAfter;

    private List<Object> currSearchAfter;

    private List<Object> nextSearchAfter;

    private List<T> datas;

    public static <T> ESPageResp<T> ofNull() {
        return ESPageResp.of(GlobalConst.ZERO_LONG, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), Collections.emptyList());
    }

    public static <T> ESPageResp<T> of(Long totalSize, List<Object> preSearchAfter, List<Object> currSearchAfter, List<Object> nextSearchAfter, List<T> datas) {
        return new ESPageResp<T>(totalSize, preSearchAfter, currSearchAfter, nextSearchAfter, datas);
    }

    public static <T, R> ESPageResp<R> copy(ESPageResp<T> pageResp, Function<List<T>, List<R>> copyFunction) {
        List<T> datas = pageResp.getDatas();
        return ByIfNotEmptyUtil.getIfNotEmptyOrElse(datas
                , () -> ESPageResp.of(pageResp.getTotalSize()
                        , pageResp.getPreSearchAfter()
                        , pageResp.getCurrSearchAfter()
                        , pageResp.getNextSearchAfter()
                        , copyFunction.apply(datas))
                , ESPageResp::ofNull
        );
    }

}
